package gruppoB;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


/**
 * 
 * Il ServerManager contiene i metodi di apertura di pagine HTML.
 * 
 * @author Gabriele Gisco responsabile Gruppo B
 *
 */
public class ServerManager {

	private ArrayList<String> risposta=new ArrayList<String>();
	public ArrayList<String> getRisposta() {
		return risposta;
	}
	public void openPage(String pageRequested) {
		File file=new File("web");
		File[] vetFile=file.listFiles();
		int i =0;
		boolean find = false;
		while (i < vetFile.length) {
			if(("/"+vetFile[i].getName()).equals(pageRequested)){
				readLineFile(vetFile[i].getName());
				find = true;
				break;
			}else {
				i++;
			}
			
		}
		if (find==false) {
			readLineFile("error.html");
		}
	}

	public void readLineFile(String fileName) {
		risposta.clear();
		BufferedReader in;
		try {
			in = new BufferedReader(new FileReader("web/"+fileName));
			risposta.add("HTTP/1.1 200 OK");
			risposta.add("Date: Tue, 01 Apr 2014 08:41:20");
			risposta.add("Content-Type: text/html; charset=utf-8");
			risposta.add("");
			
			
			String line=in.readLine();
			risposta.add(line);
			
			while (line!=null) {
				line=in.readLine();
				
				if(line!=null){
					risposta.add(line);
				}
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
